package interviewClassic150;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class LongestConsecutive {
    public int longestConsecutive(int[] nums) {
        if (nums.length == 0) return 0;

        //定义一个map，key为对应nums中的值，value为是否已经被访问过（初始化每个元素都是false）
        Map<Integer,Boolean> map = new HashMap<>();
        //初始化
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i],false);
        }
        //遍历元素
        int res = 1;
        for (int i = 0; i < nums.length; i++) {
            if (map.get(nums[i])) continue;//已经访问过，直接跳过
            //没访问过，那么分别向更大和更小方向增长
            int cur = nums[i];
            //设置为已访问
            map.put(cur,true);
            int len = 1;
            int more = cur + 1;
            int less = cur - 1;
            while (map.containsKey(more)) {
                len++;
                //设置为已访问
                map.put(more,true);
                more++;
            }
            while (map.containsKey(less)) {
                len++;
                //设置为已访问
                map.put(less,true);
                less--;
            }

            //重置结果
            res = Math.max(res,len);
        }

        return res;
    }

    @Test
    public void test() {
        System.out.println(longestConsecutive(new int[]{100,4,200,1,3,2}));
    }
}
